<?php

namespace eu\freeplace\validator;

use eu\freeplace\validator\Validator as Validator;

/**
 * Validate ISBN Numbers.
 *
 * @author Elmar Dott
 * @version 1.0
 */
class ValidateISBN {
    
    const CLASS_NAME = "ValidateISBN";
    const ISBN10 = "/^[0-9]{9,9}([0-9]|X|x)$/";
    const ISBN13 = "";

    /**
     * International Standard Book Number Test
     * @see: http://en.wikipedia.org/wiki/International_Standard_Book_Number
     * 
     * @global Logger $logger 
     */
    public function __construct() {
      global $logger;
      $logger->log("Calling instance of ".self::CLASS_NAME."()", "NOTICE");
    }
    
    /**
     * Check if an ISBN 10 Number valid.
     *
     * @param String $isbn
     * @return Boolean reult
     */
    public function testISBN10($isbn) {
        $check = false;
        $result = 0; 
        $digit = null;
        
        $isbn = str_replace("-", "", $isbn);
        $isbn = str_replace(" ", "", $isbn);
        
        $validator = Validator::getInstance();
        
        if( $validator->validate(ValidateISBN::ISBN10, $isbn) != 0) {
            for($i=0; $i<10; $i++) {
                $digit = substr($isbn, $i, 1);
                if($i==9) {
                    //Modulo 11
                    $result = $result % 11;

                    if($result == 10 && strtolower($digit) == "x") {
                        $check = true;
                    } else if ($result == $digit) {
                        $check = true;
                    }
                    
                } else {
                    $result += ($i+1) * $digit;
                }
            }//FOR
            $logMsg = self::CLASS_NAME.".testISBN10(".$isbn.") ".$check.": ".$digit." = ".$result;
        } else {
            $logMsg = self::CLASS_NAME.".testISBN10(".$isbn.") - invalid ISBN";
        }
        
        global $logger;
        $logger->log($logMsg, "DEBUG");
       
        return $check;
    }
    
    public function testISBN13($isbn) {
        
        return $isbn;
    }
}//CLASS

?>